package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.GridLayoutManager.SpanSizeLookup
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.dl7.recycler.divider.GridDivider
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.Xutils
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.common.business.pay.AliPayHelper
import com.kanshu.ksgb.fastread.doudou.common.business.pay.PayTypeSelectDialog
import com.kanshu.ksgb.fastread.doudou.common.business.pay.WxPayHelper
import com.kanshu.ksgb.fastread.doudou.common.business.pay.bean.OrderRequestParams
import com.kanshu.ksgb.fastread.doudou.common.business.pay.event.PayActionEvent
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog
import com.kanshu.ksgb.fastread.doudou.module.personal.adapter.RechargeAdapter
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.AccountInfo
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.PayConfig
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UserData
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import com.ss.android.common.lib.EventUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_charge.*
import me.drakeet.support.toast.ToastCompat
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

const val KEY_TYPE = "charge_type"

class ChargeFragment : BaseFragment() {
    private var type: Int = TYPE_CHARGE
    private var day: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            type = it.getInt(KEY_TYPE, TYPE_CHARGE)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_charge, container, false)
    }

    override fun onResume() {
        super.onResume()
        if (type == TYPE_REMOVE_AD) {
            tips_title.text = context?.getString(R.string.tips_title_remove_ad)
            tips.text = context?.getString(R.string.tips_remove_ad)
        }
        loadPayConfig()
        loadUserInfo()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        EventBus.getDefault().register(this)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        recyler_view.addItemDecoration(GridDivider(DisplayUtils.dip2px(context, 11f), DisplayUtils.dip2px(context, 9f), 2, false));
    }

    override fun onDetach() {
        super.onDetach()
        EventBus.getDefault().unregister(this)
    }

    private fun loadPayConfig() {
        val helper = RetrofitHelper.getInstance()
        val apiService = helper.createService(PersonCenterService::class.java)
        val observable: Observable<BaseResult<List<PayConfig>>> = if (type == TYPE_REMOVE_AD)
            apiService.getNoADPayConfig() else apiService.getPayConfig()
        observable.compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<List<PayConfig>>> {

                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: BaseResult<List<PayConfig>>?) {
                        val lists = t?.result?.data
                        if (lists != null) {
/*                            val lists2 = mutableListOf<PayConfig>()
                            lists2.addAll(lists)
                            val tmp = PayConfig()
                            tmp.pay_rate = "200"
                            tmp.give_fee = "20" tmp.pay_fee = "30" lists2.add(tmp)*/
                            initPayConfigs(lists)
                        } else {
                            ToastUtil.showMessage("获取充值配置信息失败 ${t?.result?.status?.msg}")
                        }

                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        ToastUtil.showMessage("获取充值配置信息失败")
                    }


                })

    }

    private val COLUM_COUNT = 2
    private var itemCount = 0

    private fun initPayConfigs(lists: List<PayConfig>) {
        val adapter = RechargeAdapter(context, lists, type)
        itemCount = lists.size
        val layoutManager = GridLayoutManager(context, COLUM_COUNT)
        layoutManager.spanSizeLookup = object : SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                if (position == (itemCount - 1) && itemCount % 2 == 1) {
                    return 2
                } else {
                    return 1
                }
            }
        }
        recyler_view.adapter = adapter
        recyler_view.layoutManager = layoutManager
        adapter.setOnItemClickListener { view, position ->
            val item = lists[position]
            if (type == TYPE_REMOVE_AD) {
                doNoADs(item)
            } else {
                doPay(item)
            }
        }
    }


    private fun doNoADs(payConfig: PayConfig) {
        day = payConfig.pay_day.toInt()
        PayTypeSelectDialog.show(activity, payConfig.total_fee.toInt(), 0, payConfig.pay_day.toInt(), 2)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handlePayActionEvent(event: PayActionEvent) {
        if (event.errCode == PayActionEvent.FINISH_PAGE) return

        setPurchase(event)

        if (event.isSuccess) {
            ToastCompat.makeText(Xutils.getContext(), R.string.ali_pay_result_success, Toast.LENGTH_SHORT).show()
            loadUserInfo()
        } else {
            // PayErrorDialog.show(activity).show()
            CustomDialog.show(activity, "失败", "充值失败，请重新充值！", object : CustomDialog.Callback {
                override fun onSure(dialog: Dialog) {
                    rePay()
                    dialog.dismiss()
                }

                override fun onCancel(dialog: Dialog) {
                    dialog.dismiss()
                }
            }, false).setCancelBtnText("知道了").setSureBtnText("重新充值")
        }
    }

    //    头条上报        EventUtils.setPurchase("支付内容类型",
    // "商品/内容名(免广告)",
    // "商品ID/内容ID",
    // "商品数量",
    // "支付渠道名 如支付宝、微信等",
    // "真实货币类型",
    // "是否成功（必须上传）",
    // "本次支付的真实货币的金额（必须上传，单位：元）")
    private fun setPurchase(event: PayActionEvent) {
        val channelName = if (event.payment == PayActionEvent.PAYMENT.WEI_XIN) {
            "微信"
        } else if (event.payment == PayActionEvent.PAYMENT.ZHI_FU_BAO) {
            "支付宝"
        } else {
            //目前只有微信和支付宝
            Log.w("Purchase","头条支付统计，错误")
            return
        }
        //商品数量
        val contentName = if (type == TYPE_REMOVE_AD) {
            "免广告"
        }else if (type == TYPE_CHARGE) {
            "充值"
        }else {
            Log.w("Purchase","头条支付统计，错误")
            return
        }
        val payInfo = MMKVDefaultManager.getInstance().payInfo

        if (!payInfo.isNullOrBlank()) {
            val info = payInfo.split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            val coin = Integer.parseInt(info[0])
            val totalFee = Integer.parseInt(info[1])
            val payType = Integer.parseInt(info[2])
            var businessType = 0
            if (info.size > 3) {
                businessType = Integer.parseInt(info[3])
            }
            EventUtils.setPurchase(null,contentName,"id_$type",1,channelName,"rmb",event.isSuccess,totalFee/100)
        }
    }

    private fun rePay() {
        val payInfo = MMKVDefaultManager.getInstance().payInfo
        if (TextUtils.isEmpty(payInfo)) return
        val info = payInfo.split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val coin = Integer.parseInt(info[0])
        val totalFee = Integer.parseInt(info[1])
        val payType = Integer.parseInt(info[2])
        var businessType = 0
        if (info.size > 3) {
            businessType = Integer.parseInt(info[3])
        }
        val params = OrderRequestParams()
        params.coin = coin
        params.day = day
        params.total_fee = totalFee
        params.pay_type = payType
        params.business_type = businessType
        params.book_id = StorageUtils.getPreference(context, Constants.SP_NAME, "charge_book_id", "")
        if (payType == Constants.PayType.TYPE_ALI) {
            val helper = AliPayHelper(activity)
            helper.payAction(params)
        } else if (payType == Constants.PayType.TYPE_WX) {
            val helper = WxPayHelper(activity)
            helper.payAction(params)
        }
    }

    private fun doPay(payConfig: PayConfig) {
        PayTypeSelectDialog.show(activity, payConfig.pay_fee.toInt() * 100, payConfig.coin.toInt())
    }

    companion object {
        const val TYPE_CHARGE = 1
        const val TYPE_REMOVE_AD = 2
        @JvmStatic
        fun newInstance(type: Int) =
                ChargeFragment().apply {
                    arguments = Bundle().apply {
                        putInt(KEY_TYPE, type)
                    }
                }
    }


    private fun loadUserInfo() {
        if (type != TYPE_CHARGE) {
            return
        }
        total_view.visibility = View.VISIBLE
        val helper = RetrofitHelper.getInstance()
        val params = mutableMapOf<String, String>()
        params["get_master_info"] = "0"
        params["get_account_info"] = "1"
        params["get_phone_info"] = "0"
        helper.createService(PersonCenterService::class.java)
                .getUserBaseInfo(params)
                .compose(this.asyncRequest())
                .subscribe(object : Observer<BaseResult<UserData>> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: BaseResult<UserData>?) {
                        val data = t?.result?.data?.account_info
                        if (data != null) {
                            updateTotalAmountView(data)
                        }
                    }

                    override fun onError(e: Throwable?) {
                    }

                });


    }

    private fun updateTotalAmountView(account_info: AccountInfo) {
        val total = account_info.account_balance;
        val spannableString = SpannableStringBuilder()
        spannableString.append("我的金额：${total} 金币")
        spannableString.setSpan(ForegroundColorSpan(mContext.resources.getColor(R.color.color_my_coin)), 5, 5 + total.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        total_view.text = spannableString


    }


}
